#include "StdAfx.h"
#include "GetHtmlContent.h"
#include "UtilConvert.h"
#include <algorithm>

CGetHtmlContent::CGetHtmlContent(void)
{
}

CGetHtmlContent::~CGetHtmlContent(void)
{
}

void CGetHtmlContent::GetBugIDList(CString strUrl, VCT_DWORD& vctList)
{
	CString strHtml;
	GetHtmlString(strUrl, strHtml);

	int nIndex = 0;
	while (true)
	{
		nIndex = strHtml.Find(BUGID_PREFIX, nIndex);
		if (nIndex == -1) break;

		nIndex +=(int)wcslen(BUGID_PREFIX);
		int nPostfix = strHtml.Find(BUGID_POSTFIX, nIndex);
		CString strBugID = strHtml.Mid(nIndex, nPostfix - nIndex);

		DWORD dwBugID = 0;
		Util::Convert::StringToDWordW(strBugID.GetBuffer(), dwBugID);
		if (vctList.empty() || dwBugID != vctList[vctList.size() - 1])
		{
			vctList.push_back(dwBugID);
		}
	}
}

void CGetHtmlContent::GetBugInfo(CString strUrl, BugInfo& stBugInfo)
{
	CString strHtml;
	GetHtmlString(strUrl, strHtml);

	int nIndex = 0;
	nIndex = strHtml.Find(BUGINFO_PREFIX, nIndex);
	nIndex = strHtml.Find(BUGINFO_PREFIX, nIndex + (int)wcslen(BUGINFO_PREFIX));

	int nStart = nIndex + (int)wcslen(BUGINFO_PREFIX);
	int nEnd = strHtml.Find(BUGINFO_PREFIX, nStart);
	CString strMd5Info = strHtml.Mid(nStart, nEnd - nStart);
	strMd5Info.Replace(_T("\r\n"), _T(" "));

	int nCurPos = 0;
	VCT_STRING vctString;
	CString strTemp = strMd5Info.Tokenize(_T(" "), nCurPos);
	while (strTemp.IsEmpty() == FALSE)
	{
		vctString.push_back(strTemp);
		strTemp = strMd5Info.Tokenize(_T(" "), nCurPos);
	}

	for (size_t i = 0; i < vctString.size(); i += 2)
	{
		FileInfo stFileInfo;
		stFileInfo.strFileName = vctString[i];
		stFileInfo.strMd5 = vctString[i+1];

		stBugInfo.vctFileMd5.push_back(stFileInfo);
	}

	std::sort(stBugInfo.vctFileMd5.begin(), stBugInfo.vctFileMd5.end());
}

void CGetHtmlContent::GetHtmlString(CString strUrl, CString& strOut)
{
	CHttpFile* oFile = (CHttpFile*)m_oHttpSession.OpenURL(strUrl);
	CString strXmlContent;
	CString strTemp;

	DWORD dwLen = 0;
	BYTE* pBuffer = new BYTE[1024 + 1];

	CStringA strBuffer;

	while (dwLen = oFile->Read(pBuffer, 1024))
	{
		strBuffer.Append((char*)pBuffer, dwLen);
	}
	delete []pBuffer;

	strOut = Util::Convert::Utf8ToWS((char*)strBuffer.GetBuffer(), strBuffer.GetLength());
}
